#!/usr/bin/env node
const child_process = require("child_process");
const fs = require("fs");

const command = "git status";
const trimReg = /(\ +)|([ ])|([\r\n]|(["]))/g;
let commitFile = child_process.execSync(command).toString();
commitFile = commitFile.split("\n").filter((item) => item);
const fileList = [];
let index = 0;
while (
  commitFile[index] !== "Changes to be committed:" &&
  index < commitFile.length
)
  index++;
for (let i = index; i < commitFile.length; i++) {
  if (
    ["Changes not staged for commit:", "Untracked files:"].includes(
      commitFile[i].trim()
    )
  )
    break;
  const name = commitFile[i].trim().split(":")[1];
  if (!name) continue;
  if (name.includes("->")) {
    fileList.push(decodeURI(name.split("->")[1].replace(trimReg, "")));
    continue;
  }
  fileList.push(decodeURI(name.replace(trimReg, "")));
}
//敏感信息列表
const sensitiveInformationList = [
  "jyeontu的密码",
  "jyeontu的AppId",
  "jyeontu的账号",
  "jyeontuUser",
  "jyeontuPassword",
];

const editFiles = [];
for (const file of fileList) {
  if (!fs.existsSync(file)) continue;
  const fileTxt = fs.readFileSync(file, "utf8").split("\n");
  for (let textLine = 0; textLine < fileTxt.length; textLine++) {
    const txt = fileTxt[textLine];
    for (const sensitiveInformation of sensitiveInformationList) {
      if (txt.includes(sensitiveInformation)) {
        editFiles.push(
          `\x1b[31m${file}:${textLine + 1}\x1b[0m -> ${sensitiveInformation}`
        );
      }
    }
  }
}
if (editFiles.length > 0) {
  console.log("\x1b[31m请删除敏感信息后再次提交:\x1b[0m");
  console.log(editFiles.join("\n"));
  process.exit(1);
}
process.exit(0);
